#include "DirectXPrimitive.h"

Primitive::Primitive (int Numverts, LPDIRECT3DDEVICE9 DrawDevice)
{
	VertList = new Vertex[Numverts];
	Device = DrawDevice;
	D3DXMatrixIdentity(&Transformation);
	NumVerts = Numverts;
}

Primitive::~Primitive (void)
{
}

void Primitive::Draw (D3DPRIMITIVETYPE Type, int NumPrims)
{
	if ((VertBuffer) && (Device))
	{
		Device->SetFVF(FVF);
		Device->SetTransform(D3DTS_WORLD, &Transformation);
		Device->SetStreamSource(0, VertBuffer, 0, sizeof(Vertex));
		Device->DrawPrimitive(Type, 0, NumPrims);
	}
}

void Primitive::SetVert (UINT Vert, Vertex& NewVert)
{
	if ((Vert >= 1) && (Vert <= NumVerts))
		VertList[Vert - 1] = NewVert;
	if (Device)
		BuildBuffer();
}

void Primitive::SetDrawDevice (LPDIRECT3DDEVICE9 DrawDevice)
{
	Device = DrawDevice;
}

void Primitive::Rotate (float Xdeg, float Ydeg, float Zdeg)
{
	D3DXMATRIX TempX, TempY, TempZ;
	D3DXMatrixRotationX (&TempX, Xdeg);
	D3DXMatrixRotationY (&TempY, Ydeg);
	D3DXMatrixRotationZ (&TempZ, Zdeg);
	Rotation = (TempX * TempY * TempZ);
	Transformation *= Rotation;
}

void Primitive::Translate (float X, float Y, float Z)
{
	D3DXMatrixIdentity(&Translation);
	D3DXMatrixTranslation(&Translation, X, Y, Z);
	Transformation *= Translation;
}

void Primitive::Scale (float XVal, float YVal, float ZVal)
{
	D3DXMatrixIdentity(&Scalar);
	D3DXMatrixScaling(&Scalar, XVal, YVal, ZVal);
	Transformation *= Scalar;
}

void Primitive::ZeroTransformation (void)
{
	D3DXMatrixIdentity(&Transformation);
}

void Primitive::BuildBuffer (void)
{
	Device->CreateVertexBuffer(NumVerts * sizeof(Vertex),
							   0, FVF, D3DPOOL_MANAGED, &VertBuffer, NULL);
	VertBuffer->Lock(0, 0, (void**)&Pvoid, 0);
	memcpy(Pvoid, VertList, NumVerts * sizeof(Vertex));
	VertBuffer->Unlock();
}